package com.kevin.v2.spring.formework.aop.proxy;

import com.kevin.v2.spring.formework.aop.intercept.KvMethodInvocation;
import com.kevin.v2.spring.formework.aop.support.KvAdviseSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class KvJDKAopProxy implements KvAopProxy, InvocationHandler {

   private KvAdviseSupport config;

   public KvJDKAopProxy (KvAdviseSupport config) {
      this.config = config;
   }

   /**
    * 把原生对象传递进来
    *
    * @return
    */
   @Override
   public Object getProxy () {
      return getProxy(config.getTargetClass().getClassLoader());
   }

   @Override
   public Object getProxy (ClassLoader classLoader) {
      return Proxy.newProxyInstance(classLoader, config.getTargetClass().getInterfaces(), this);
   }

   @Override
   public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {

      List<Object> interceptorAndDynamicMethodMatcher =
              config.getInterceptorAndJdkInterceptionAdvice(method, config.getTargetClass());
      KvMethodInvocation im = new KvMethodInvocation(
              proxy, method,
              config.getTarget(), config.getTargetClass(),
              args, interceptorAndDynamicMethodMatcher);

      return im.proceed();
   }
}
